﻿using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Infrastructure.Helpers.PwdHelper
{
    /// <summary>
    /// 使用PBKDF2-SHA1加密密码散列。
    /// </summary>
    public class PwdHelper
    {
        //密钥
        private const string AESKey = "rVA7xlZDLByAHon8";//密钥,128位          

        //默认密钥向量
        private static byte[] IV = Encoding.UTF8.GetBytes("gq7zQ5yhxtsoHcg7");

        /// <summary>
        /// AES加密算法
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <returns>返回加密后的密文字节数组</returns>
        public static string Encrypt(string plainText)
        {

            if (string.IsNullOrEmpty(plainText))
            {
                return "";
            }
            //分组加密算法
            SymmetricAlgorithm des = Rijndael.Create();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
            //设置密钥及密钥向量
            des.Key = Encoding.UTF8.GetBytes(AESKey);
            des.IV = IV;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
            cs.Close();
            ms.Close();
            return Convert.ToBase64String(cipherBytes);
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="EStr">密文字节数组</param>
        /// <returns>返回解密后的字符串</returns>
        public static string Decrypt(string EStr)
        {
            byte[] cipherText = Convert.FromBase64String(EStr);
            SymmetricAlgorithm des = Rijndael.Create();
            des.Key = Encoding.UTF8.GetBytes(AESKey);
            des.IV = IV;
            byte[] decryptBytes = new byte[cipherText.Length];
            MemoryStream ms = new MemoryStream(cipherText);
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
            cs.Read(decryptBytes, 0, decryptBytes.Length);
            cs.Close();
            ms.Close();
            return Encoding.UTF8.GetString(decryptBytes);
        }




    }
}